﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;

namespace Noria.Web.Utility
{
    /// <summary>
    /// Summary description for rolling
    /// </summary>
    public class LogHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            if (context.Request.QueryString.Count > 0)
            {
                var name = context.Request.QueryString["name"];
                var size = int.Parse(context.Request.QueryString["size"]);
                if (size == -1)
                    size = int.MaxValue;

                
                string path = context.Server.MapPath("logs");
                var log = Path.Combine(path, name);
                List<string> buffer = new List<string>();

                using (var sr = new StreamReader(
                    System.IO.File.Open(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    string line ;
                    
                    while ((line = sr.ReadLine()) != null)
                    {
                        buffer.Add(line);
                    }
                }

                var skipped = buffer.Count - size;
                if (skipped < 0)
                    skipped = 0;

                JArray data = new JArray(buffer.Skip(skipped));
                context.Response.Write(data.ToString());
            }
            else
            {
                JArray data = new JArray();
                string path = context.Server.MapPath("logs");
                var logs = Directory.GetFiles(path, "*.log*");
                for (int i = 0; i < logs.Length; i++)
                {
                    FileInfo fi = new FileInfo(logs[i]);
                    data.Add(JObject.FromObject(new { name = fi.Name, size = fi.Length }));
                }
                context.Response.Write(data.ToString());
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}